﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.IO;

namespace Utils
{
    public static class XMLParser
    {
        public static List<Dictionary<string,string>> XMLToDictionaryCollection(this string xmlString)
        {
            try
            {
                xmlString = xmlString.Replace("&", "and");
                byte[] textBuffer = Encoding.UTF8.GetBytes(xmlString);
                List<Dictionary<string, string>> allItems;
                using (MemoryStream ms = new MemoryStream(textBuffer))
                {
                    using (TextReader tr = new StreamReader(ms))
                    {
                        var doc = XDocument.Load(tr, LoadOptions.None);
                        var rootNodes = doc.Root.DescendantNodes().OfType<XElement>();
                        allItems = new List<Dictionary<string, string>>();
                        foreach (var node in rootNodes)
                        {
                            Dictionary<string, string> attr = new Dictionary<string, string>();
                            if (node.HasAttributes)
                            {
                                //attr.Add(node.FirstAttribute.Name, node.FirstAttribute.Value);
                                XAttribute attribute = node.FirstAttribute;
                                while (attribute != null)
                                {
                                    attr.Add(attribute.Name.LocalName, attribute.Value);
                                    attribute = attribute.NextAttribute;
                                }
                            }
                            allItems.Add(attr);
                        }
                    }
                }
                return allItems;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}
